<?php

global $base_url;

govideo_set_background(govideo_get_background('page'));
if (arg(0) == 'blog')
    govideo_set_background(govideo_get_background('blog'));

drupal_add_js('
    ddsmoothmenu.init({
      arrowimages: {down:[\'downarrowclass\', \'' . $base_url . '/' . drupal_get_path('theme', 'govideo') . '/images/down.gif\', 30], right:[\'rightarrowclass\', \'' . $base_url . '/' . drupal_get_path('theme', 'govideo') . '/images/right.gif\']},
	    mainmenuid: "smoothmenu1",
	    orientation: \'h\',
	    classname: \'ddsmoothmenu\',
	    //customtheme: ["#1c5a80", "#18374a"],
	    contentsource: "markup"
    });
    (function ($) {$(document).ready(function(){
    $(function() {
	    var zIndexNumber = 0;
      $(\'.flowplayer\').each(function() {
        $(this).css(\'zIndex\', zIndexNumber);
      });
7	  });
	  });})(jQuery);
	', array('type' => 'inline', 'scope' => 'footer', 'weight' => 5));

/* govideo_breadcrumb($breadcrumb) */

function govideo_breadcrumb($breadcrumb) {
    //drupal_set_message('<pre>'. check_plain(print_r($breadcrumb, 1)) .'</pre>');
    if (!empty($breadcrumb['breadcrumb'])) {
        $out = '';
        $n = count($breadcrumb['breadcrumb']);
        $i = 1;
        foreach ($breadcrumb['breadcrumb'] as $data) {
            if ($i == $n)
                $out .= '<li class="last">' . $data . '</li>';
            else
                $out .= '<li>' . $data . '</li>';
            $i++;
        }
        return '<h5>' . t('You are here') . ':</h5><ul>' . $out . '</ul>';
    }
}

function govideo_flowplayer($variables) {
    $config = $variables['config'];
    $id = $variables['id'];
    $attributes = $variables['attributes'];

    $r = rand();
    // Prepare the ID.
    $id = drupal_clean_css_identifier($id) . $r;

    // Prepare the attributes, passing in the flowplayer class.
    if (isset($attributes['class'])) {
        $attributes['class'] .= ' flowplayer';
    } else {
        $attributes['class'] = 'flowplayer';
    }
    $attributes['style'] = 'width:675px;height:438px;';
    $attributes = drupal_attributes($attributes);
    $config['wmode'] = 'opaque';
    // Add the JavaScript to handle the element.
    flowplayer_add('#' . $id, $config);

    // Return the markup.
    return "<div id='$id' $attributes></div>";
}

/*
  function govideo_video($variables) {

  $themed_output = '';
  if (empty($variables['item']['fid']))
  return '';
  $field_settings = $variables['field']['settings'];
  $instance_settings = $variables['instance']['settings'];
  // Only needs to be ran if they are converting videos
  if (isset($field_settings['autoconversion']) && $field_settings['autoconversion']) {
  module_load_include('inc', 'video', '/includes/conversion');
  $conversion = new video_conversion;
  if ($video = $conversion->load_job($variables['item']['fid'])) {
  if ($video->video_status == VIDEO_RENDERING_ACTIVE || $video->video_status == VIDEO_RENDERING_PENDING) {
  return theme('video_inprogress');
  } else if ($video->video_status == VIDEO_RENDERING_FAILED) {
  return theme('video_conversion_failed');
  }
  }
  }
  // Setup our video object
  //drupal_set_message('<pre>'. check_plain(print_r($variables, 1)) .'</pre>');
  module_load_include('inc', 'video', '/includes/video_helper');
  $video_helper = new video_helper;
  $video = $video_helper->video_object($variables);
  // Lets spit out our theme based on the extension
  $defaults = video_video_extensions();
  $theme_function = variable_get('video_extension_' . $video->player, $defaults[$video->player]);

  // Lets do some special handling for our flv files, HTML5 to accomdate multiple players.
  $video->variables = $variables['entity'];
  switch ($theme_function) {
  case 'video_play_flv':
  return theme('video_flv', array('video' => $video, 'themed_output' => $themed_output));
  break;
  case 'video_play_html5':

  return theme('video_html5', array('video' => $video, 'themed_output' => $themed_output));
  break;
  default:
  return theme($theme_function, array('video' => $video, 'themed_output' => $themed_output));
  break;
  }
  }
 */

function govideo_video_formatter_player($variables) {
    //drupal_set_message('<pre>'. check_plain(print_r($variables, 1)) .'</pre>');
    $themed_output = '';
    if (empty($variables['item']['fid']))
        return '';
    $field_settings = $variables['field']['settings'];
    $instance_settings = $variables['instance']['settings'];
    // Only needs to be ran if they are converting videos
    if (isset($field_settings['autoconversion']) && $field_settings['autoconversion']) {
        $factory = new TranscoderAbstractionAbstractFactory();
        $transcoder = $factory->getProduct();
        $transcoder->setInput($variables['item']);
        if ($video = $transcoder->loadJob()) {
            if ($video->video_status == VIDEO_RENDERING_ACTIVE || $video->video_status == VIDEO_RENDERING_PENDING) {
                return theme('video_inprogress');
            } else if ($video->video_status == VIDEO_RENDERING_FAILED) {
                return theme('video_conversion_failed');
            }
        }
    }
    // Setup our video object
    module_load_include('inc', 'video', '/includes/VideoHelper');
    $video_helper = new VideoHelper;
    $video = $video_helper->video_object($variables);
    // override player dimentions
    if (isset($variables['player_dimensions']) && !empty($variables['player_dimensions'])) {
        $player_dimensions = explode('x', $variables['player_dimensions']);
        $video->player_width = trim($player_dimensions[0]);
        $video->player_height = trim($player_dimensions[1]);
    }
    // Lets spit out our theme based on the extension
    //original
    //$defaults = video_video_extensions();
    //Gassa changed
    $defaults = array(
        'divx' => 'video_play_divx',
        'mkv' => 'video_play_divx',
        'mov' => 'video_play_quicktime',
        '3gp' => 'video_play_quicktime',
        '3g2' => 'video_play_quicktime',
        'mp4' => 'video_play_quicktime',
        'm4v' => 'video_play_quicktime',
        'rm' => 'video_play_realmedia',
        'f4v' => 'video_play_flv',
        'flv' => 'video_play_flv',
        'swf' => 'video_play_flash',
        'dir' => 'video_play_dcr',
        'dcr' => 'video_play_dcr',
        'asf' => 'video_play_windowsmedia',
        'wmv' => 'video_play_windowsmedia',
        'avi' => 'video_play_windowsmedia',
        'mpg' => 'video_play_windowsmedia',
        'mpeg' => 'video_play_windowsmedia',
        'ogg' => 'video_play_theora',
        'ogv' => 'video_play_theora',
        'webm' => 'video_play_theora'
    );
    $theme_function = variable_get('video_extension_' . $video->player, $defaults[$video->player]);

    // Lets do some special handling for our flv files, HTML5 to accomdate multiple players.
    switch ($theme_function) {
        case 'video_play_flv':
            return theme('video_flv', array('video' => $video, 'themed_output' => $themed_output));
            break;
        case 'video_play_html5':
            $video->node = $variables['entity'];
            if (arg(0) == 'embed' and arg(2)) {
                $d = explode('x', arg(2));
                if (isset($d[0]) and is_numeric($d[0])) {
                    $video->node->emplayer_width = $d[0];
                }
                if (isset($d[1]) and is_numeric($d[1])) {
                    $video->node->emplayer_height = $d[1];
                }
            }
            return theme('video_html5', array('video' => $video, 'themed_output' => $themed_output));
            break;
        default:
            return theme($theme_function, array('video' => $video, 'themed_output' => $themed_output));
            break;
    }
}

function govideo_video_html5($variables) {
    //drupal_set_message('<pre>'. check_plain(print_r($variables, 1)) .'</pre>');
    $themed_output = NULL;
    $video = $variables['video'];

    /* echo */ $video->html5_player = variable_get('video_extension_' . $video->player . '_html5_player', '');
    switch ($video->html5_player) {
        case 'video':

            return theme('video_play_html5', array('video' => $video, 'themed_output' => $themed_output));
            break;
        case 'videojs':
            $items = _video_object_to_array($video->files);
            $items +=array('thumbnail' => (array) $video->thumbnail);
            $attributes = array();
            $attributes['width'] = $video->width;
            $attributes['height'] = $video->height;
            return theme('videojs', array('items' => $items, 'player_id' => 'video-' . $video->fid, 'attributes' => $attributes));
            break;
    }
}

function govideo_set_bic($j) {
    $blocks = block_get_blocks_by_region('banner_in_category_' . $j);
    $block = render($blocks);
    return $block;
}

function govideo_set_suggestions() {
    $blocks = block_get_blocks_by_region('suggestions');
    $block = render($blocks);
    return $block;
}

function govideo_pager($variables) {
    $tags = $variables['tags'];
    $element = $variables['element'];
    $parameters = $variables['parameters'];
    $quantity = $variables['quantity'];
    global $pager_page_array, $pager_total;

    // Calculate various markers within this pager piece:
    // Middle is used to "center" pages around the current page.
    $pager_middle = ceil($quantity / 2);
    // current is the page we are currently paged to
    $pager_current = $pager_page_array[$element] + 1;
    // first is the first page listed by this pager piece (re quantity)
    $pager_first = $pager_current - $pager_middle + 1;
    // last is the last page listed by this pager piece (re quantity)
    $pager_last = $pager_current + $quantity - $pager_middle;
    // max is the maximum page number
    $pager_max = $pager_total[$element];
    // End of marker calculations.
    // Prepare for generation loop.
    $i = $pager_first;
    if ($pager_last > $pager_max) {
        // Adjust "center" if at end of query.
        $i = $i + ($pager_max - $pager_last);
        $pager_last = $pager_max;
    }
    if ($i <= 0) {
        // Adjust "center" if at start of query.
        $pager_last = $pager_last + (1 - $i);
        $i = 1;
    }
    // End of generation loop preparation.

    $li_first = theme('pager_first', array('text' => (isset($tags[0]) ? $tags[0] : t('«')), 'element' => $element, 'parameters' => $parameters));
    $li_previous = theme('pager_previous', array('text' => (isset($tags[1]) ? $tags[1] : t('‹')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
    $li_next = theme('pager_next', array('text' => (isset($tags[3]) ? $tags[3] : t('›')), 'element' => $element, 'interval' => 1, 'parameters' => $parameters));
    $li_last = theme('pager_last', array('text' => (isset($tags[4]) ? $tags[4] : t('»')), 'element' => $element, 'parameters' => $parameters));

    if ($pager_total[$element] > 1) {
        if ($li_first) {
            $items[] = array(
                'class' => array('pager-first'),
                'data' => $li_first,
            );
        }
        if ($li_previous) {
            $items[] = array(
                'class' => array('pager-previous'),
                'data' => $li_previous,
            );
        }

        // When there is more than one page, create the pager list.
        if ($i != $pager_max) {
            if ($i > 1) {
                $items[] = array(
                    'class' => array('pager-ellipsis'),
                    'data' => '…',
                );
            }
            // Now generate the actual pager piece.
            for (; $i <= $pager_last && $i <= $pager_max; $i++) {
                if ($i < $pager_current) {
                    $items[] = array(
                        'class' => array('pager-item'),
                        'data' => theme('pager_previous', array('text' => $i, 'element' => $element, 'interval' => ($pager_current - $i), 'parameters' => $parameters)),
                    );
                }
                if ($i == $pager_current) {
                    $items[] = array(
                        'class' => array('pager-current'),
                        'data' => $i,
                    );
                }
                if ($i > $pager_current) {
                    $items[] = array(
                        'class' => array('pager-item'),
                        'data' => theme('pager_next', array('text' => $i, 'element' => $element, 'interval' => ($i - $pager_current), 'parameters' => $parameters)),
                    );
                }
            }
            if ($i < $pager_max) {
                $items[] = array(
                    'class' => array('pager-ellipsis'),
                    'data' => '…',
                );
            }
        }
        // End generation.
        if ($li_next) {
            $items[] = array(
                'class' => array('pager-next'),
                'data' => $li_next,
            );
        }
        if ($li_last) {
            $items[] = array(
                'class' => array('pager-last'),
                'data' => $li_last,
            );
        }
        return '<h2 class="element-invisible">' . t('Pages') . '</h2>' . theme('item_list', array(
                    'items' => $items,
                    'attributes' => array('class' => array('pager')),
                ));
    }
}

function govideo_set_tabs($bid, $title, $content, $isout = false) {
    static $tabs = array();
    if ($bid) {
        $tabs[$bid]->bid = $bid;
        $tabs[$bid]->title = $title;
        $tabs[$bid]->content = $content;
    }
    if ($isout and isset($tabs) and is_array($tabs)) {
        $out_t = '';
        $out_c = '';
        $i = 0;
        foreach ($tabs as $data) {
            if (!$i)
                $ac = ' class="current"'; else
                $ac = '';
            $out_t .= '<li><a' . $ac . ' rel="tab_sidebar_' . $data->bid . '">' . $data->title . '</a></li>';
            $out_c .= '<div style="display: none;" id="tab_sidebar_' . $data->bid . '" class="tab_sidebar_list">' . $data->content . '</div>';
            $i++;
        }
        return '<div class="tabs"><div class="tab_menu_container"><ul id="tab_menu">' . $out_t . '</ul><div class="clear"></div></div><div class="tab_container"><div class="tab_container_in">' . $out_c . '<div class="clear"></div></div></div><div class="clear"></div></div>';
    }
}

function govideo_set_home_video_right($bid, $title, $content, $isout = FALSE) {
    global $base_url;
    static $tabs = array();
    if ($bid) {
        $tabs[$bid]->bid = $bid;
        $tabs[$bid]->title = $title;
        $tabs[$bid]->content = $content;
    }
    if ($isout and isset($tabs) and is_array($tabs)) {
        $out_t = '';
        $out_c = '';
        $out_v = govideo_set_home_video_left(FALSE, TRUE);
        $i = 0;
        foreach ($tabs as $datar) {
            if (!$i)
                $ac = ' class="selected"'; else
                $ac = '';
            $out_t .= '<li><a href="#idTab' . $datar->bid . '"' . $ac . '><span>' . $datar->title . '</span></a></li>';
            $out_c .= '<div id="idTab' . $datar->bid . '" class="tabssection"><div class="css-scrollbar simple">' . $datar->content . '</div></div>';
            $i++;
        }
        return '<div id="banner">' . $out_v . '<div id="paginate-slider2"><div class="usual"><ul class="idTabs">' . $out_t . '</ul>' . $out_c . '</div></div><div class="clear"></div></div><script type="text/javascript" src="' . $base_url . '/' . drupal_get_path('theme', 'govideo') . '/js/banner.js"></script>';
    }
}

function govideo_set_home_video_left($content, $isout = false) {
    static $resl = '';
    if ($content) {
        $resl .= $content;
    }
    if ($isout and $resl) {
        return '<div id="slider2" class="leftsecbanner">' . $resl . '</div>';
    }
}

function govideo_top($type = 'search') {

    $header = array(
        array('data' => t('Count'), 'field' => 'count', 'sort' => 'desc'),
        array('data' => t('Message'), 'field' => 'message')
    );
    $count_query = db_select('watchdog');
    $count_query->addExpression('COUNT(DISTINCT(message))');
    $count_query->condition('type', $type);

    $query = db_select('watchdog', 'w')->extend('PagerDefault')->extend('TableSort');
    $query->addExpression('COUNT(wid)', 'count');
    $query = $query
            ->fields('w', array('message', 'variables'))
            ->condition('w.type', $type)
            ->groupBy('message')
            ->groupBy('variables')
            ->limit(30)
            ->orderByHeader($header);
    $query->setCountQuery($count_query);
    $result = $query->execute();

    $t = '';
    foreach ($result as $dblog) {
        $a = unserialize($dblog->variables);
        $t .= '<li>' . l($a['%keys']/* .' ('.$dblog->count.')' */, 'search/node/' . $a['%keys'], array('html' => TRUE)) . '</li>';
    }

    return '<div class="topsearches"><h5>' . t('Top Searches') . '</h5><ul>' . $t . '</ul><a href="' . url('most_viewed') . '" class="buttonone"><span>' . t('Most Viewed Videos') . '</span></a><a href="' . url('videos') . '" class="buttonone"><span>' . t('Recent Videos') . '</span></a></div>';
}

function govideo_set_background($content, $isout = false) {
    static $res = '';
    if ($content) {
        $res = $content;
    }
    if ($isout and $res) {
        $file = file_create_url($res);
        return ' style="background-image:url(' . $file . ');"';
    }
}

function govideo_get_background($bundle, $field_name = 'field_background', $entity_type = 'taxonomy_term') {
    $datadef = unserialize(
            db_select('field_config', 'f')
                    ->fields('f', array('data'))
                    ->condition('field_name', $field_name . '_' . $bundle)
                    ->range(0, 1)
                    ->execute()
                    ->fetchField()
    );
    if (isset($datadef['settings']['default_image'])) {
        $file = file_load($datadef['settings']['default_image']);
        $out = $file->uri;
    } else {
        $out = FALSE;
    }

    return $out;
}

function govideo_get_count_nodes($type = 'video') {
    $n = db_select('node');
    $n->addExpression('COUNT(nid)', 'count');
    $n->condition('type', $type);
    $n->condition('status', 1);
    $n = $n->execute()->fetchField();
    return $n;
}

/* govideo_user_menu_top($logged_in) */

function govideo_user_menu_top($logged_in, $front_page) {
    global $user;
    $output = '';
    //<li><a href="#">Mature Warning: On</a></li>
    if (!$logged_in) {
        $output .= '<li>' . l('Log in', 'user') . '</li>';
        $output .= '<li>' . l('Register', 'user/register') . '</li>';
    } else {
        $output .= '<li>' . l('Log out', 'user/logout') . '</li>';
        $output .= '<li>' . l('Account', 'user/' . $user->uid) . '</li>';
    }
    return '<ul><li class="first"><a href="' . check_url($front_page) . '" name="toppage">' . t('Home') . '</a></li>' . $output . '</ul>';
}

function govideo_menu_tree($tree) {
    return '<ul>' . $tree['tree'] . '</ul>';
}

function govideo_menu_link(array $variables) {
    $element = $variables['element'];
    $sub_menu = '';
    if ($element['#below']) {
        $sub_menu = drupal_render($element['#below']);
    } //else {
    //$element['#localized_options']['attributes']['class'] += 'staticlinks';
    //}
    $output = l($element['#title'], $element['#href'], $element['#localized_options']);
    return '<li>' . $output . $sub_menu . "</li>\n";
}

/**
 * Generate the HTML output for a menu item and submenu.
 *
 * @ingroup themeable
 */
function govideo_menu_item($link, $has_children, $menu = '', $in_active_trail = FALSE, $extra_class = NULL) {
    return '<li>' . $link . $menu . "</li>\n";
}

/* Node */
/*
  function govideo_get_node($type = 'type') {
  static $node = false;
  if (!$node and arg(0) == 'node' and is_numeric(arg(1))){
  $node = db_fetch_array(db_query('SELECT * FROM {node} where nid = %d',arg(1)));
  }
  return $node[$type];
  }

  function govideo_get_node_style() {
  static $node = false;
  if (!isset($node) and arg(0) == 'node' and is_numeric(arg(1)) and !arg(2)){
  $node = node_load(arg(1));
  return $node->field_style[0]['value'];
  } else {
  return 'n';
  }
  }
 */

function govideo_truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE, &$ll = 0) {

    if (drupal_strlen($string) <= $len) {
        return $string;
    }

    if ($dots) {
        $len -= 4;
    }

    if ($wordsafe) {
        $string = drupal_substr($string, 0, $len + 1); // leave one more character
        if ($last_space = strrpos($string, ' ')) { // space exists AND is not on position 0
            $string = substr($string, 0, $last_space);
            $ll = $last_space;
        } else {
            $string = drupal_substr($string, 0, $len);
            $ll = $len;
        }
    } else {
        $string = drupal_substr($string, 0, $len);
        $ll = $len;
    }

    if ($dots) {
        $string .= ' ...';
    }

    return $string;
}

